<%--
  - Copyright 2011 Angel Sanadinov
  -
  - This file is part of VBox WMI.
  -
  - VBox WMI is free software: you can redistribute it and/or modify
  - it under the terms of the GNU General Public License as published by
  - the Free Software Foundation, either version 3 of the License, or
  - (at your option) any later version.
  -
  - VBox WMI is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  - GNU General Public License for more details.
  -
  - You should have received a copy of the GNU General Public License
  - along with VBox WMI.  If not, see <http://www.gnu.org/licenses/>.
  --%>

<%@page import="java.net.URL"%>
<%@page import="Beans.Responses.DataRetrievalComponents.ServerDataComponent"%>
<%@page import="Beans.Requests.DataRetrieval.ServersDataRetrievalRequest"%>
<%@page import="Utilities.UIFunctions"%>
<%@page import="Beans.Requests.DataRetrieval.MachinesDataRetrievalRequest"%>
<%@page import="Beans.Responses.DataRetrievalComponents.MachineDataComponent"%>
<%@page import="Beans.Responses.DataRetrievalResponse"%>
<%@page import="Utilities.ParameterNames"%>
<%@page import="Utilities.ParameterNames.Service"%>
<%@page import="Utilities.Constants.SendingRequestResult"%>
<%@page import="Managers.Utilities.User"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="jstlc"%>
<%@taglib uri="/WEB-INF/tlds/pagePrintingTags.tld" prefix="p"%>
<%@page contentType="text/html" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%
    //retrieves user data from the session
    User userSessionData = (User)session.getAttribute(ParameterNames.SESSION_USER_OBJECT);

    String targetServerAddress = null;  //address of the server on which the target machine resides
    String targetMachinePorts = null;   //VRDP ports for the target machine
    String portIDOptions = "";          //HTML <option>s for the machine ports
    String failureReason = null;        //reason for failed page load
    boolean isActionAllowed = false;    //denotes whether the action is allowed

    if(request.getParameter("id") != null)
    {
        DataRetrievalResponse<MachineDataComponent> machineData = null;

        //builds the machine data retrieval request
        MachinesDataRetrievalRequest machineRequest =
                new MachinesDataRetrievalRequest(userSessionData.getUserData().getUserId(),
                                                 userSessionData.getCurrentServerId(),
                                                 request.getParameter("id"));

        //attempts to send the request and retrieves the result
        if(UIFunctions.sendServiceRequest(request, response, machineRequest, Service.DATA_RETRIEVAL) 
                == SendingRequestResult.OK)
        {
            machineData = (DataRetrievalResponse<MachineDataComponent>)
                    UIFunctions.retrieveServiceResponse(request, Service.DATA_RETRIEVAL);
        }
        else
            ;

        //checks if the machine data retrieval was successful
        if(machineData != null && machineData.isValid())
        {
            //checks if the VRDP server for that machine is enabled
            if(machineData.getResource().getVrdpSettings().getServerState())
            {
                DataRetrievalResponse<ServerDataComponent> serverData = null;
                //builds the server data retrieval request
                ServersDataRetrievalRequest serverRequest =
                        new ServersDataRetrievalRequest(userSessionData.getUserData().getUserId(),
                                                        userSessionData.getCurrentServerId());

                //attempts to send the request and retreives a response
                if(UIFunctions.sendServiceRequest(request, response, serverRequest, Service.DATA_RETRIEVAL)
                        == SendingRequestResult.OK)
                {
                    serverData = (DataRetrievalResponse<ServerDataComponent>)
                            UIFunctions.retrieveServiceResponse(request, Service.DATA_RETRIEVAL);
                }
                else
                    ;

                //checks if the retrieved server data is valid
                if(serverData != null && serverData.isValid())
                {
                    try
                    {
                        //retrieves the server address
                        targetServerAddress = (new URL(serverData.getResource().getServerAddress())).getHost();
                        //retrieves the machine VRDP ports
                        targetMachinePorts = machineData.getResource().getVrdpSettings().getServerPorts();

                        //builds the ports <option>s list
                        String[] ports = targetMachinePorts.split(",");
                        for(int i = 0; i < ports.length; i++)
                            portIDOptions += "<option value=\"" + i + "\">" + ports[i] + "</option>\n";

                        isActionAllowed = true;
                    }
                    catch(Exception e){}
                }
                else
                    failureReason = "Host server data retrieval failed";
            }
            else
                failureReason = "The VRDP server on the specified machine is not enabled.";
        }
        else
            failureReason = "Machine data retrieval failed.";
    }
    else
        failureReason = "Machine UUID not specified, please select a machine first.";

    //meta tags for cache control; should make sure that the page is not cached
    String cachingMetaTags = "<meta http-equiv=\"Expires\" content=\"0\">\n"
                             + "<meta http-equiv=\"Cache-Control\" content =\"no-cache\">\n"
                             + "<meta http-equiv=\"Cache-Control\" content =\"no-store, must-revalidate, max-age=0\">\n"
                             + "<meta http-equiv=\"Cache-Control\" content =\"post-check=0, pre-check=0\">\n"
                             + "<meta http-equiv=\"Pragma\" content=\"no-cache\">\n";

    //additional JavaScript for the rdp client
    String additionalScripts = "<script type=\"text/javascript\" src=\"js/webRDP/webclient.js\"></script>\n"
                               + "<script type=\"text/javascript\" src=\"js/webRDP/swfobject.js\"></script>\n"
                               + "<script type=\"text/javascript\" src=\"js/webRDP/webRDPManagement.js\"></script>\n";
%>
<p:printPageHeader pageName="Web RDP Client" pageId="webRDP" userSessionData="<%= userSessionData %>"
                   additionalMetaData="<%= cachingMetaTags %>" additionalScriptsData="<%= additionalScripts %>" />

<jstlc:choose>
    <jstlc:when test="<%= isActionAllowed && targetServerAddress != null && targetMachinePorts != null %>">
    <div>
        <a class="actionLink" href="noJavaScript.jsp" onclick="return changePopupVisibility('rdpConfigurationModification');">Configure</a>
        <a class="actionLink" href="noJavaScript.jsp" onclick="return rdpManager.connect(this)">Connect</a>
        <a class="actionLink" href="noJavaScript.jsp" onclick="return rdpManager.sendCAD()">Ctrl + Alt + Del</a>
        Scan codes:
        <a class="actionLink" href="noJavaScript.jsp" onclick="return rdpManager.sendScancodes()">Send</a>
        <a class="actionLink" href="noJavaScript.jsp" onclick="return changePopupVisibility('rdpScancodesModification');">Set</a>
    </div>
    <div id="rdpMessagesElement"></div>
    <div id="rdpClientElementContainer">
        <div id="rdpClientElement"></div>
        <script type="text/javascript">
            var rdpManager = new WebRDPManager('rdpClientElement', 'rdpMessagesElement', 'rdpManager',
                                               '<%= targetServerAddress %>',
                                               '<%= targetMachinePorts %>');
            rdpManager.setInitialConfiguration(0, '', '', '800', '600');
        </script>
    </div>
    <form class="resourceModification" id="rdpScancodesModification" action="noJavaScript.jsp">
        Scan Codes: <input type="text" name="scancodes"><br>
        <a class="actionLink" href="noJavaScript.jsp"
           onclick="rdpManager.setScancodes('rdpScancodesModification');
                    return changePopupVisibility('rdpScancodesModification');">Set</a>
        <a class="actionLink" href="#"
           onclick="document.getElementById('rdpScancodesModification').elements['scancodes'].value='';
                    return false">Clear</a>
    </form>
    <form class="resourceModification" id="rdpConfigurationModification" action="noJavaScript.jsp">
        <table>
            <tr><td>Server ID:</td><td><input type="text" size="3" name="" value="<%= userSessionData.getCurrentServerId() %>" readonly></td></tr>
            <tr><td>Connection Port:</td><td><select name="machinePortId"><%= portIDOptions %></select></td>
                <td><a href="noJavaScript.jsp" onclick="return false;"
                       title="A virtual machine listents on only one of its ports.">?</a></td></tr>
            <tr><td>Guest Username:</td><td><input type="text" name="logonUsername"></td></tr>
            <tr><td>Guest Password:</td><td><input type="password" name="logonPassword"></td></tr>
            <tr><td>Window Size:</td><td><input type="text" name="displayWidth" size="5" value="800">x
                                 <input type="text" name="displayHeight" size="5" value="600"></td></tr>
        </table>
        <a class="actionLink" href="noJavaScript.jsp"
           onclick="rdpManager.updateConfiguration('rdpConfigurationModification');
                    return changePopupVisibility('rdpConfigurationModification');">Update</a>
    </form>
    </jstlc:when>
    <jstlc:otherwise>
        Error: <%= failureReason %>
    </jstlc:otherwise>
</jstlc:choose>
<p:printPageFooter/>
